package zy.controller;

import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zy.dto.LoginDto;
import zy.entity.AppCategory;
import zy.entity.AppInfo;
import zy.entity.AppVersion;
import zy.server.AppInfoServer;
import zy.server.AppVersionServer;
import zy.server.CategoryServer;
import zy.server.LogingUserServer;
import zy.sessionUtil.SsionUtils;
import zy.vo.LoginVo;
import zy.vo.Rsutilvo;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RequestMapping("/appInfo")
@RestController
public class LoginController {
    @Autowired
    LogingUserServer userServer;

    @Autowired
    CategoryServer categoryServer;

    @Autowired
    AppInfoServer appInfoServer;

    @Autowired
    AppVersionServer appVersionServer;

    //登录
    @PostMapping("/Login")
    public Rsutilvo Login(@RequestBody LoginDto loginDto){
        LoginVo loginVo=null;
        try {
            loginVo=userServer.Login(loginDto);
        } catch (Exception e) {
            e.printStackTrace();
            return Rsutilvo.error(e.getMessage());
        }
        return Rsutilvo.success("登录成功",loginVo);
    }

    //注销
    @PostMapping("/zhuXiao")
    public Rsutilvo zhuXiao(HttpServletRequest request){
        String token = request.getHeader("token");
        SsionUtils.delToken(token);
        return Rsutilvo.success("注销成功",null);
    }

    //三级联动
    @PostMapping("/shanJi")
    public Rsutilvo shanJi(Integer parentId){
            List<AppCategory> shanJi=categoryServer.shanJi(parentId);
            return Rsutilvo.success("",shanJi);
    }

    //分页查询（把上面输入框里面的值都放进分页里面）
    @PostMapping("/fenYe")
    public Rsutilvo fenYe(@RequestBody AppInfo appInfo, @RequestParam(defaultValue = "1") Integer pageNum, HttpServletRequest request){
        PageInfo<AppInfo> pageInfo=appInfoServer.fenYe(appInfo,pageNum);
            return Rsutilvo.success("",pageInfo);
    }

    //apk验证
    //直接把appInfo整个拿过来 然后获取里面的appId 如果有id说明是修改操作
    //然后用id查询数据库里面的单条数据因为要获取它apk的名称与前端传递过来
    // 的apk名称进行比对如果一样就证明没改就直接reten true 就行了
    //如果修改了就进行正常的比对 查询这个appInfo名称是否存在（查询条数）
    // 有的话就已经存在没有就返回一个true 说明apk不存在


    //首先要知道前端要传递过来的数据有id一个apkName一个
    //然后写server在server里面写上面的操作
    @PostMapping("/yanZheng")
    public  Rsutilvo yanZheng(@RequestBody AppInfo appInfo){
        Boolean panDuan=appInfoServer.yanZheng(appInfo);
        if (panDuan==true){
            return Rsutilvo.success("",null);
        }else {
            return Rsutilvo.error("");
        }
    }

    @PostMapping("/updAndadd")
    public Rsutilvo updAndadd(AppInfo appInfo, MultipartFile logo, HttpServletRequest request){
        //获取token来获取到底有没有id有就是修改没有就是新增
        String token = request.getHeader("token");
        String[] split = token.split("-");
        String newFileName=null;
        if (logo!=null && !logo.isEmpty()) {
            String realPath = request.getServletContext().getRealPath("/logoImg");
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String originalFilename = logo.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if (logo.getSize() > 1024 * 500) {
                throw new RuntimeException("文件不能超过500k");
            } else if (extension.equalsIgnoreCase("jpg") ||
                    extension.equalsIgnoreCase("png") ||
                    extension.equalsIgnoreCase("jpeg") ||
                    extension.equalsIgnoreCase("gif")
            ) {
                newFileName = UUID.randomUUID() + "." + extension;
                File file1 = new File(realPath, newFileName);
                appInfo.setLogopicpath("/logoImg/" + newFileName);
                try {
                    logo.transferTo(file1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                throw new RuntimeException("必须是图片格式才行");
            }
        }
        if (appInfo.getId()==null){
            appInfo.setCreatedby(Long.valueOf(split[2]));
            appInfo.setDevid(Long.valueOf(split[2]));
            appInfo.setCreationdate(new Date());
            appInfo.setStatus(1L);
            appInfoServer.add(appInfo);
        }else {
            appInfo.setModifyby(Long.valueOf(split[2]));
            appInfo.setModifydate(new Date());
            appInfoServer.update(appInfo);
        }

        return Rsutilvo.success("",null);
    }


    //要传递一个id 和request 因为要获取api的路径和图片的路径 删除
        @PostMapping("/del/{id}")
        public Rsutilvo del(@PathVariable Long id, HttpServletRequest request){
            appInfoServer.delserver(id,request);
            return Rsutilvo.success("",null);
        }

        //上下架
    //上架和审核可以写在一起因为上架和审核都只需要去修改一下状态
        @PostMapping("/shangJia/{Id}")
        public Rsutilvo shangJia(@PathVariable Long Id){
            AppInfo appInfo=appInfoServer.AppInfoAll(Id);
            if (appInfo.getStatus()==4L){
                appInfo.setStatus(5L);
            }else if(appInfo.getStatus()==5L || appInfo.getStatus()==2L){
                appInfo.setStatus(4L);
            }
            appInfoServer.update(appInfo);
            return Rsutilvo.success("",null);
        }

        //查询版本
        @PostMapping("/AllVersion")
        public Rsutilvo AllVersion(Long appid){
          List<AppVersion> appVersions=appVersionServer.AllVersion(appid);
          return Rsutilvo.success("",appVersions);
        }

        //查询版本里的appInfo表
        @PostMapping("/appInfoId")
        public Rsutilvo appInfoId( Long appid){
            AppInfo appInfo=appInfoServer.AppInfoId(appid);
            return Rsutilvo.success("",appInfo);
        }

        //新增版本号
        @PostMapping("/addVersion")
        public Rsutilvo addVersion(AppVersion appVersion,MultipartFile apkFile,HttpServletRequest request){
            //获取token来获取到底有没有id有就是修改没有就是新增
            String token = request.getHeader("token");
            String[] split = token.split("-");
            String newFileName=null;
            if (apkFile!=null && !apkFile.isEmpty()){
                String realPath = request.getServletContext().getRealPath("/apkFileImg");
                File file=new File(realPath);
                if (!file.exists()){
                    file.mkdirs();
                }
                String originalFilename = apkFile.getOriginalFilename();
                String extension = FilenameUtils.getExtension(originalFilename);
                if (apkFile.getSize()>1024*500){
                    throw new RuntimeException("文件不能超过500k");
                }
                if (extension.equalsIgnoreCase("apk")
                ){
                    newFileName = UUID.randomUUID() + "." + extension;
                    File file1 = new File(realPath, newFileName);
                    appVersion.setDownloadlink("/apkFileImg"+newFileName);
                    try {
                        apkFile.transferTo(file1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //添加版本 不止要添加版本 还要添加
                    appVersion.setCreatedby(Long.valueOf(split[2]));
                    appVersion.setCreationdate(new Date());
                    appVersion.setPublishstatus(3L);
                    appVersionServer.add(appVersion);
                    AppInfo appInfo=new AppInfo();
//                    Long maxId=Long.valueOf(appVersionServer.maxId());
//                    appVersion.setId(maxId);
                    appInfo.setId(appVersion.getAppid());
                    appInfo.setVersionid(appVersion.getId());
                    appInfoServer.update(appInfo);
            }
            return Rsutilvo.success("",null);
        }

    @PostMapping("/shenHe")
    public Rsutilvo shenHe(@RequestBody AppInfo appInfo,@RequestParam Long statusId){
        appInfo.setStatus(statusId);
        appInfoServer.update(appInfo);
        return Rsutilvo.success("",null);
    }



}
